package cn.itcast.lucene.demo;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;

public class CreateIndex {

    public static void main(String[] args) throws IOException {
        System.out.println("1111111111111");
        System.out.println("2222");
        System.out.println("33333333333333");
        System.out.println("dev11111111");
        System.out.println("56");
        System.out.println("322");
        System.out.println("322");

        //createIndex();
        deleteIndex();
        return;

    }

    private static void createIndex() throws IOException {
        FSDirectory directory = FSDirectory.open(new File("F:\\index"));
        //Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_10_3);
        Analyzer analyzer = new IKAnalyzer();
        IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_4_10_3,analyzer);
        IndexWriter indexWriter = new IndexWriter(directory, conf);

        File fileDir = new File("F:\\searchsource");
        File[] files = fileDir.listFiles();
        for (File file : files) {
            Document document = new Document();
            document.add(new TextField("fileName",file.getName(), Field.Store.YES));
            document.add(new TextField("fileContent", FileUtils.readFileToString(file), Field.Store.YES));
            document.add(new LongField("fileSize",FileUtils.sizeOf(file), Field.Store.YES));
            document.add(new TextField("filePath",file.getPath(), Field.Store.YES));
            indexWriter.addDocument(document);
        }

        indexWriter.commit();
        indexWriter.close();
    }

    private static void deleteIndex() throws IOException {
        FSDirectory directory = FSDirectory.open(new File("F:\\index"));
        //Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_10_3);
        Analyzer analyzer = new IKAnalyzer();
        IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_4_10_3,analyzer);
        IndexWriter indexWriter = new IndexWriter(directory, conf);
        indexWriter.deleteDocuments(new Term("fileName","传智播客"));
        //indexWriter.deleteAll();
        indexWriter.commit();
        indexWriter.close();
    }
}
